package com.kc.controller;

import com.aliyuncs.exceptions.ClientException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kc.ExceptionHandler.UndowException;
import com.kc.bean.UserAccount;
import com.kc.service.IRegistAndLogin;
import com.kc.service.PhoneGetService;
import com.kc.util.JWTutil;
import com.kc.util.ParamEnum;
import com.kc.util.ResponesBean;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController
public class RegistAndLogin {

    @Resource
    private ResponesBean responesBean;

    @Resource
    private PhoneGetService phoneGetService;

    @Resource
    private IRegistAndLogin iRegistAndLogin;

    @PostMapping("register")
    public ResponesBean register(@RequestBody String Account) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        UserAccount.Account account = mapper.readValue(Account, UserAccount.Account.class);
        UserAccount userAccount = account.getUserAccount();
        responesBean = iRegistAndLogin.register(userAccount,account.getCode(),account.getPassword());
        return responesBean;
    }

    @PostMapping("login")
    public ResponesBean login(String phone,String password){
        responesBean = iRegistAndLogin.login(phone,password);
        return responesBean;
    }

    @Transactional
    @GetMapping("getphone")
    public ResponesBean getphone(String phone){
        try {
            String code = phoneGetService.PhoneGet(phone, ParamEnum.registered);
            responesBean.setAll(200,"验证码发送成功如下",code);
            return responesBean;
        } catch (ClientException e) {
            throw new UndowException("请检查手机号重新发送");
        }catch (NullPointerException e){
            throw new UndowException("手机号为空请重新输入");
        }
    }

    @GetMapping("/bzd")
    public ResponesBean bzd(HttpServletRequest request){
        String token = request.getHeader("AcessToken");
        String role = JWTutil.GetPayload(token,"groud");
        responesBean.setAll(200,"success,测试成功",role);
        return responesBean;
    }
}
